﻿/*
 * Erstellt mit SharpDevelop.
 * Benutzer: Christian
 * Datum: 03.05.2010
 * Zeit: 22:27
 * 
 * Sie können diese Vorlage unter Extras > Optionen > Codeerstellung > Standardheader ändern.
 */
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using System.Xml;

using MediaInfoLib;

namespace MovieExplorer
{
    /// <summary>
    /// Description of MainForm.
    /// </summary>
    public partial class MainForm : Form
    {
        private Settings _Settings = null;
        private string _SettingsFilename = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "settings.xml");

        public MainForm()
        {
            //
            // The InitializeComponent() call is required for Windows Forms designer support.
            //
            InitializeComponent();

            _Settings = new Settings();
            _Settings.Load(_SettingsFilename);

            RefreshRecordingList();
            RefreshMyMoviesList();
        }

        private void ShowHeadMessage(string message)
        {
            ShowHeadMessage(message, 1);
        }

        private void ShowHeadMessage(string message, int status)
        {
            /*switch (status)
            {
               case 0:
                  lblHeadMessages.ForeColor = Color.Black;
                  break;
               case 1:
                  lblHeadMessages.ForeColor = Color.Red;
                  break;
               case 2:
                  lblHeadMessages.ForeColor = Color.Green;
                  break;
               case 3:
                  lblHeadMessages.ForeColor = Color.Blue;
                  break;
               case 4:
                  lblHeadMessages.ForeColor = Color.Yellow;
                  break;
            }*/

            int i = listMessages.Items.Add(message);
            listMessages.SelectedIndex = i;
            listMessages.Refresh();
        }

        private void ShowMessage(string message)
        {
            ShowMessage(message, 1);
        }

        private void ShowMessage(string message, int status)
        {
            /*switch (status)
            {
               case 0:
                  lblMessages.ForeColor = Color.Black;
                  break;
               case 1:
                  lblMessages.ForeColor = Color.Red;
                  break;
               case 2:
                  lblMessages.ForeColor = Color.Green;
                  break;
               case 3:
                  lblMessages.ForeColor = Color.Blue;
                  break;
               case 4:
                  lblMessages.ForeColor = Color.Yellow;
                  break;
            }*/

            int i = listMessages.Items.Add(message);
            listMessages.SelectedIndex = i;
            listMessages.Refresh();
        }


        private List<Recording> _Recordings = new List<Recording>();

        private void RefreshRecordingList()
        {
            try
            {
                listViewRecordings.Items.Clear();

                _Recordings = MovieInformation.GetRecordings(_Settings.ConfigDirectory, _Settings.RecordingsDBFile, _Settings.SQLiteV3Recordings, _Settings.UTF8);

                foreach (Recording rec in _Recordings)
                {
                    ListViewItem item = listViewRecordings.Items.Add(rec.Title);
                    item.SubItems.Add(rec.Channel);

                    if (!File.Exists(rec.Filename))
                    {
                        item.BackColor = Color.Red;
                    }

                    string duration = "?";
                    // dauert zu lange
                    /*if(File.Exists(rec.Filename))
                    {
                       MediaInfo mi = new MediaInfo();
                  
                       mi.Open(rec.Filename);
                  
                       duration = mi.Get(StreamKind.General, 0, "Duration/String3");
                       duration = duration.Substring(0, 5);
                     
                       mi.Close();               
                    }*/

                    item.SubItems.Add(duration);
                }

                tsslRecordings.Text = "Aufnahmen: " + _Recordings.Count.ToString();
            }
            catch (Exception ex)
            {
                ShowMessage(ex.Message);
            }
        }

        private List<Movie> _Movies = new List<Movie>();

        private void RefreshMyMoviesList()
        {
            try
            {
                listViewMyMovies.Items.Clear();

                _Movies = MovieInformation.GetMoviesFromDB(_Settings.ConfigDirectory, _Settings.MyMoviesDBFile, _Settings.SQLiteV3MyMovies, _Settings.UTF8);

                string[] movieDirs = Directory.GetDirectories(_Settings.MyMoviesDirectory, "*", SearchOption.TopDirectoryOnly);

                foreach (Movie movie in _Movies)
                {
                    ListViewItem item = listViewMyMovies.Items.Add(movie.Title);

                    if (!File.Exists(movie.Filename))
                    {
                        item.BackColor = Color.Red;
                    }

                    string duration = "?";
                    // dauert zu lange
                    /*if(File.Exists(movie.Filename))
                    {
                       MediaInfo mi = new MediaInfo();
                  
                       mi.Open(movie.Filename);
                  
                       duration = mi.Get(StreamKind.General, 0, "Duration/String3");
                       duration = duration.Substring(0, 5);
                     
                       mi.Close();               
                    }*/

                    item.SubItems.Add(duration);

                    item.SubItems.Add(movie.Filename);
                }

                tsslMyMovies.Text = "Filme: " + _Movies.Count;

                // neue Verzeichnisse prüfen
                foreach (string movieDir in movieDirs)
                {
                    bool bFound = false;

                    foreach (Movie movie in _Movies)
                    {
                        if (Path.GetFullPath(movieDir).ToLower().TrimEnd(new char[] { '\\' }).Equals(Path.GetFullPath(movie.Path).ToLower().TrimEnd(new char[] { '\\' })))
                        {
                            bFound = true;
                        }
                    }

                    if (!bFound)
                    {
                        if (MessageBox.Show("Soll das Verzeichnis \"" + movieDir + "\" mit aufgenommen werden?", "Verzeichnis hinzufügen", MessageBoxButtons.YesNo) == DialogResult.Yes)
                        {
                            DirectoryInfo dirInfo = new DirectoryInfo(movieDir);

                            ShowHeadMessage("Add new movie \"" + dirInfo.Name + "\"");

                            if (Directory.Exists(movieDir))
                            {
                                string newMovieDir = movieDir;
                                DirectoryInfo dirInfo2 = new DirectoryInfo(movieDir);
                                string topdirname = dirInfo2.Name;
                                if (topdirname.IndexOf("'") >= 0)
                                {
                                    newMovieDir = Path.Combine(_Settings.MyMoviesDirectory, topdirname.Replace("'", ""));
                                    Directory.Move(movieDir, newMovieDir);
                                }

                                MovieInformation movieInfo = GetMovieInfos(dirInfo.Name, newMovieDir);
                                if (movieInfo != null)
                                {
                                    // todo: Videodateiendungen prüfen
                                    string[] dirFiles = Directory.GetFiles(newMovieDir);

                                    if (dirFiles.Length > 0)
                                    {
                                        for (int u = 0; u < dirFiles.Length; u++)
                                        {
                                            FileInfo ufi = new FileInfo(dirFiles[u]);
                                            if (ufi.Extension.Equals(".mpg") ||
                                               ufi.Extension.Equals(".mkv") ||
                                               ufi.Extension.Equals(".wmv") ||
                                               ufi.Extension.Equals(".ts") ||
                                               ufi.Extension.Equals(".avi") ||
                                               ufi.Extension.Equals(".mpeg") ||
                                               ufi.Extension.Equals(".mov"))
                                            {
                                                movieInfo.filename = dirFiles[u].Replace("\"", "");
                                                break;
                                            }
                                        }

                                    }
                                    movieInfo.path = newMovieDir.Replace("\"", "");

                                    GetMediaInfo(movieInfo.filename, ref movieInfo);

                                    movieInfo.title = movieInfo.title.Replace("\"", "");
                                    movieInfo.Description = movieInfo.Description.Replace("\"", "");
                                    movieInfo.AlternativeTitles = movieInfo.AlternativeTitles.Replace("\"", "");

                                    if (_Settings.DBUsed)
                                    {
                                        movieInfo.AddToDB(_Settings.ConfigDirectory, _Settings.MyMoviesDBFile, _Settings.SQLiteV3MyMovies, _Settings.UTF8);
                                    }
                                    else
                                    {
                                        movieInfo.WriteInfoFile(newMovieDir);
                                    }
                                }
                            }
                            else
                            {
                                throw new Exception("Directory " + movieDir + " does not exist");
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ShowMessage(ex.Message);
            }
        }

        protected virtual void OnBtnDeleteMyMovieClicked(object sender, System.EventArgs e)
        {
            listMessages.Items.Clear();

            try
            {
                this.Cursor = Cursors.WaitCursor;

                foreach (int index in listViewMyMovies.SelectedIndices)
                {
                    Movie movie = _Movies[index];

                    if (MessageBox.Show("Soll der Film \"" + movie.Title + "\" wirklich gelöscht werden?", "Film löschen", MessageBoxButtons.YesNo) == DialogResult.Yes)
                    {
                        if (Directory.Exists(movie.Path))
                        {
                            Directory.Delete(movie.Path, true);

                            ShowMessage("Directory \"" + movie.Path + "\" deleted!");
                        }

                        MovieInformation.RemoveMovieFromDB(movie.ID, _Settings.ConfigDirectory, _Settings.MyMoviesDBFile, _Settings.SQLiteV3MyMovies, _Settings.UTF8);

                        ShowMessage("Movie \"" + movie.Title + "\" removed from Database!");
                    }
                }
            }
            catch (Exception ex)
            {
                ShowMessage(ex.Message);
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }

            RefreshMyMoviesList();
        }

        protected virtual void OnBtnDeleteRecordingClicked(object sender, System.EventArgs e)
        {
            listMessages.Items.Clear();

            try
            {
                this.Cursor = Cursors.WaitCursor;

                foreach (int index in listViewRecordings.SelectedIndices)
                {
                    Recording rec = _Recordings[index];

                    if (MessageBox.Show("Soll die Aufnahme \"" + rec.Title + "\" wirklich gelöscht werden?", "Aufnahme löschen", MessageBoxButtons.YesNo) == DialogResult.Yes)
                    {
                        if (File.Exists(rec.Filename))
                        {
                            File.Delete(rec.Filename);
                            ShowMessage("File \"" + rec.Filename + "\" deleted!");

                            FileInfo fi = new FileInfo(rec.Filename);
                            if (File.Exists(fi.DirectoryName + fi.Name + ".log"))
                            {
                                File.Delete(fi.DirectoryName + fi.Name + ".log");
                                ShowMessage("File \"" + fi.DirectoryName + fi.Name + ".log" + "\" deleted!");
                            }
                            if (File.Exists(fi.DirectoryName + fi.Name + ".txt"))
                            {
                                File.Delete(fi.DirectoryName + fi.Name + ".txt");
                                ShowMessage("File \"" + fi.DirectoryName + fi.Name + ".txt" + "\" deleted!");
                            }
                        }

                        MovieInformation.RemoveRecordFromDB(rec.ID, _Settings.ConfigDirectory, _Settings.RecordingsDBFile, _Settings.SQLiteV3Recordings, _Settings.UTF8);

                        ShowMessage("Recording \"" + rec.Title + "\" removed from Database!");
                    }
                }
            }
            catch (Exception ex)
            {
                ShowMessage(ex.Message);
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }

            RefreshRecordingList();
        }

        protected virtual void OnBtnMoveRecordingsClicked(object sender, System.EventArgs e)
        {
            listMessages.Items.Clear();

            try
            {
                this.Cursor = Cursors.WaitCursor;

                int i = 0;
                foreach (int index in listViewRecordings.SelectedIndices)
                {
                    Recording rec = _Recordings[index];

                    i++;
                    ShowHeadMessage("Move recording \"" + rec.Title + "\" " + i.ToString() + "/" + listViewRecordings.SelectedIndices.Count.ToString());

                    FileInfo fi = new FileInfo(rec.Filename);

                    String strFilenameSrc = rec.Filename;
                    String strDirnameDest = _Settings.MyMoviesDirectory + rec.Title.Replace("'", "") + @"\";
                    String strFilenameDest = strDirnameDest + rec.Title.Replace("'", "") + fi.Extension;

                    if (!Directory.Exists(strDirnameDest))
                    {
                        Directory.CreateDirectory(strDirnameDest);
                    }

                    if (File.Exists(strFilenameSrc))
                    {
                        File.Move(strFilenameSrc, strFilenameDest);

                        MovieInformation movieInfo = GetMovieInfos(rec.Title, strDirnameDest);
                        if (movieInfo != null)
                        {
                            movieInfo.filename = strFilenameDest.Replace("\"", "");
                            movieInfo.path = strDirnameDest.Replace("\"", "");

                            ShowMessage("get videofile media informations ...");

                            GetMediaInfo(strFilenameDest, ref movieInfo);

                            movieInfo.title = movieInfo.title.Replace("\"", "");
                            movieInfo.Description = movieInfo.Description.Replace("\"", "");
                            movieInfo.AlternativeTitles = movieInfo.AlternativeTitles.Replace("\"", "");

                            if (_Settings.DBUsed)
                            {
                                movieInfo.AddToDB(_Settings.ConfigDirectory, _Settings.MyMoviesDBFile, _Settings.SQLiteV3MyMovies, _Settings.UTF8);
                                MovieInformation.RemoveRecordFromDB(rec.ID, _Settings.ConfigDirectory, _Settings.RecordingsDBFile, _Settings.SQLiteV3Recordings, _Settings.UTF8);
                            }
                            else
                            {
                                movieInfo.WriteInfoFile(strDirnameDest);
                            }
                        }
                    }
                    else
                    {
                        throw new Exception("File " + strFilenameSrc + " does not exist");
                    }
                }
            }
            catch (Exception ex)
            {
                ShowMessage(ex.Message);
            }
            finally
            {
                ShowMessage("get movie informations finished");

                this.Cursor = Cursors.Default;
            }

            RefreshRecordingList();
        }

        protected virtual void OnBtnUpdateMyMoviesClicked(object sender, System.EventArgs e)
        {
            listMessages.Items.Clear();

            try
            {
                this.Cursor = Cursors.WaitCursor;

                int i = 0;
                foreach (int index in listViewMyMovies.SelectedIndices)
                {
                    Movie movie = _Movies[index];
                    //movie.Path = @"F:\Neuer Ordner\Database\Test";

                    i++;
                    ShowHeadMessage("Update movie \"" + movie.Title + "\" " + i.ToString() + "/" + listViewMyMovies.SelectedIndices.Count.ToString());

                    if (Directory.Exists(movie.Path))
                    {
                        MovieInformation movieInfo = GetMovieInfos(movie.Title, movie.Path);
                        if (movieInfo != null)
                        {
                            movieInfo.filename = movie.Filename.Replace("\"", "");
                            movieInfo.path = movie.Path.Replace("\"", "");

                            ShowMessage("get videofile media informations ...");

                            GetMediaInfo(movieInfo.filename, ref movieInfo);

                            movieInfo.title = movieInfo.title.Replace("\"", "");
                            movieInfo.Description = movieInfo.Description.Replace("\"", "");
                            movieInfo.AlternativeTitles = movieInfo.AlternativeTitles.Replace("\"", "");

                            if (_Settings.DBUsed)
                            {
                                movieInfo.UpdateDB(movie.ID, _Settings.ConfigDirectory, _Settings.MyMoviesDBFile, _Settings.SQLiteV3MyMovies, _Settings.UTF8);
                            }
                            else
                            {
                                movieInfo.WriteInfoFile(movie.Path);
                            }
                        }
                    }
                    else
                    {
                        throw new Exception("Directory " + movie.Path + " does not exist");
                    }
                }
            }
            catch (Exception ex)
            {
                ShowMessage(ex.Message);
            }
            finally
            {
                ShowMessage("get movie informations finished");

                this.Cursor = Cursors.Default;
            }

            RefreshMyMoviesList();
        }

        /*			<score>3</score>
        07.      <popularity>3</popularity>
        08.      <translated>true</translated>
        09.      <language>en</language>
        10.      <name>Transformers</name>
        11.      <alternative_name>The Transformers</alternative_name>
        12.      <type>movie</type>
        13.      <id>1858</id>
        14.      <imdb_id>tt0418279</imdb_id>
        15.      <url>http://www.themoviedb.org/movie/1858<;/url>
        16.      <rating>7.0</rating>
        17.      <certification>PG-13</certification>
        18.      <overview>The Earth is caught in the middle of an intergalactic war between two races of robots, the heroic Autobots and the evil Decepticons, which are able to change into a variety of objects, including cars, trucks, planes and other technological creations.</overview>
        19.      <released>2007-07-04</released>
        20.      <images>
        21.        <image type="poster" url="http://i2.themoviedb.org/posters/304/4bc91347017a3c57fe007304/transformers-original.jpg" size="original" id="4bc91347017a3c57fe007304"/>
        22.        <image type="poster" url="http://i3.themoviedb.org/posters/304/4bc91347017a3c57fe007304/transformers-mid.jpg" size="mid" id="4bc91347017a3c57fe007304"/>
        23.        <image type="poster" url="http://i1.themoviedb.org/posters/304/4bc91347017a3c57fe007304/transformers-cover.jpg" size="cover" id="4bc91347017a3c57fe007304"/>
        24.        <image type="poster" url="http://i3.themoviedb.org/posters/304/4bc91347017a3c57fe007304/transformers-thumb.jpg" size="thumb" id="4bc91347017a3c57fe007304"/>
        25.        <image type="backdrop" url="http://i2.themoviedb.org/backdrops/2ce/4bc91339017a3c57fe0072ce/transformers-original.jpg" size="original" id="4bc91339017a3c57fe0072ce"/>
        26.        <image type="backdrop" url="http://i2.themoviedb.org/backdrops/2ce/4bc91339017a3c57fe0072ce/transformers-poster.jpg" size="poster" id="4bc91339017a3c57fe0072ce"/>
        27.        <image type="backdrop" url="http://i3.themoviedb.org/backdrops/2ce/4bc91339017a3c57fe0072ce/transformers-thumb.jpg" size="thumb" id="4bc91339017a3c57fe0072ce"/>
        28.      </images>
        29.      <last_modified_at>2010-04-26 03:26:14</last_modified_at> */

        /*<OpenSearchDescription xmlns:opensearch="http://a9.com/-/spec/opensearch/1.1/">
        002.  <opensearch:Query searchTerms="187"/>
        003.  <opensearch:totalResults>1</opensearch:totalResults>
        004.  <movies>
        005.    <movie>
        006.      <popularity>3</popularity>
        007.      <translated>true</translated>
        008.      <language>en</language>
        009.      <name>Sin City</name>
        010.      <alternative_name></alternative_name>
        011.      <type>movie</type>
        012.      <id>187</id>
        013.      <imdb_id>tt0401792</imdb_id>
        014.      <url>http://www.themoviedb.org/movie/187<;/url>
        015.      <overview>The first of three films based on the beautiful comic world of Frank Miller. Sin City depicts the comic book almost page for page with its heavy contrast black and white extremely violent and graphic imagery. Sin City is set in a dangerous and dark Basin City where corruption, sex and violence is everyday life.</overview>
        016.      <rating>6.8</rating>
        017.      <tagline>There is no justice without sin.</tagline>
        018.      <certification>R</certification>
        019.      <released>2005-04-01</released>
        020.      <runtime>124</runtime>
        021.      <budget>40000000</budget>
        022.      <revenue>158733820</revenue>
        023.      <homepage>http://www.sincitythemovie.com/<;/homepage>
        024.      <trailer>http://www.youtube.com/watch?v=80<;/trailer>
        025.      <categories>
        026.        <category type="genre" url="http://themoviedb.org/genre/crime" name="Crime"/>
        027.        <category type="genre" url="http://themoviedb.org/genre/drama" name="Drama"/>
        028.        <category type="genre" url="http://themoviedb.org/genre/thriller" name="Thriller"/>
        029.      </categories>
        030.      <studios>
        031.        <studio url="http://www.themoviedb.org/company/20" name="Miramax Films"/>
        032.        <studio url="http://www.themoviedb.org/company/334" name="Dimension"/>
        033.      </studios>
        034.      <countries>
        035.        <country url="http://www.themoviedb.org/country/us" name="United States of America" code="US"/>
        036.      </countries>
        037.      <images>
        038.        <image type="poster" url="http://i2.themoviedb.org/posters/68c/4bc904e9017a3c57fe00168c/sin-city-original.jpg" size="original" id="4bc904e9017a3c57fe00168c"/>
        039.        <image type="poster" url="http://i1.themoviedb.org/posters/68c/4bc904e9017a3c57fe00168c/sin-city-mid.jpg" size="mid" id="4bc904e9017a3c57fe00168c"/>
        040.        <image type="poster" url="http://i2.themoviedb.org/posters/68c/4bc904e9017a3c57fe00168c/sin-city-cover.jpg" size="cover" id="4bc904e9017a3c57fe00168c"/>
        041.        <image type="poster" url="http://i2.themoviedb.org/posters/68c/4bc904e9017a3c57fe00168c/sin-city-thumb.jpg" size="thumb" id="4bc904e9017a3c57fe00168c"/>
        042.        <image type="poster" url="http://i3.themoviedb.org/posters/69b/4bc904ee017a3c57fe00169b/sin-city-original.jpg" size="original" id="4bc904ee017a3c57fe00169b"/>
        043.        <image type="poster" url="http://i1.themoviedb.org/posters/69b/4bc904ee017a3c57fe00169b/sin-city-mid.jpg" size="mid" id="4bc904ee017a3c57fe00169b"/>
        044.        <image type="poster" url="http://i1.themoviedb.org/posters/69b/4bc904ee017a3c57fe00169b/sin-city-cover.jpg" size="cover" id="4bc904ee017a3c57fe00169b"/>
        045.        <image type="poster" url="http://i2.themoviedb.org/posters/69b/4bc904ee017a3c57fe00169b/sin-city-thumb.jpg" size="thumb" id="4bc904ee017a3c57fe00169b"/>
        046.        <image type="poster" url="http://i1.themoviedb.org/posters/6a0/4bc904ef017a3c57fe0016a0/sin-city-original.jpg" size="original" id="4bc904ef017a3c57fe0016a0"/>
        047.        <image type="poster" url="http://i2.themoviedb.org/posters/6a0/4bc904ef017a3c57fe0016a0/sin-city-mid.jpg" size="mid" id="4bc904ef017a3c57fe0016a0"/>
        048.        <image type="poster" url="http://i1.themoviedb.org/posters/6a0/4bc904ef017a3c57fe0016a0/sin-city-cover.jpg" size="cover" id="4bc904ef017a3c57fe0016a0"/>
        049.        <image type="poster" url="http://i2.themoviedb.org/posters/6a0/4bc904ef017a3c57fe0016a0/sin-city-thumb.jpg" size="thumb" id="4bc904ef017a3c57fe0016a0"/>
        050.        <image type="poster" url="http://i3.themoviedb.org/posters/6a5/4bc904f1017a3c57fe0016a5/sin-city-original.jpg" size="original" id="4bc904f1017a3c57fe0016a5"/>
        051.        <image type="poster" url="http://i3.themoviedb.org/posters/6a5/4bc904f1017a3c57fe0016a5/sin-city-mid.jpg" size="mid" id="4bc904f1017a3c57fe0016a5"/>
        052.        <image type="poster" url="http://i3.themoviedb.org/posters/6a5/4bc904f1017a3c57fe0016a5/sin-city-cover.jpg" size="cover" id="4bc904f1017a3c57fe0016a5"/>
        053.        <image type="poster" url="http://i3.themoviedb.org/posters/6a5/4bc904f1017a3c57fe0016a5/sin-city-thumb.jpg" size="thumb" id="4bc904f1017a3c57fe0016a5"/>
        054.        <image type="poster" url="http://i1.themoviedb.org/posters/696/4bc904eb017a3c57fe001696/sin-city-original.jpg" size="original" id="4bc904eb017a3c57fe001696"/>
        055.        <image type="poster" url="http://i2.themoviedb.org/posters/696/4bc904eb017a3c57fe001696/sin-city-mid.jpg" size="mid" id="4bc904eb017a3c57fe001696"/>
        056.        <image type="poster" url="http://i3.themoviedb.org/posters/696/4bc904eb017a3c57fe001696/sin-city-cover.jpg" size="cover" id="4bc904eb017a3c57fe001696"/>
        057.        <image type="poster" url="http://i3.themoviedb.org/posters/696/4bc904eb017a3c57fe001696/sin-city-thumb.jpg" size="thumb" id="4bc904eb017a3c57fe001696"/>
        058.        <image type="poster" url="http://i2.themoviedb.org/posters/691/4bc904ea017a3c57fe001691/sin-city-original.jpg" size="original" id="4bc904ea017a3c57fe001691"/>
        059.        <image type="poster" url="http://i2.themoviedb.org/posters/691/4bc904ea017a3c57fe001691/sin-city-mid.jpg" size="mid" id="4bc904ea017a3c57fe001691"/>
        060.        <image type="poster" url="http://i1.themoviedb.org/posters/691/4bc904ea017a3c57fe001691/sin-city-cover.jpg" size="cover" id="4bc904ea017a3c57fe001691"/>
        061.        <image type="poster" url="http://i1.themoviedb.org/posters/691/4bc904ea017a3c57fe001691/sin-city-thumb.jpg" size="thumb" id="4bc904ea017a3c57fe001691"/>
        062.        <image type="poster" url="http://i1.themoviedb.org/posters/6aa/4bc904f4017a3c57fe0016aa/sin-city-original.png" size="original" id="4bc904f4017a3c57fe0016aa"/>
        063.        <image type="poster" url="http://i3.themoviedb.org/posters/6aa/4bc904f4017a3c57fe0016aa/sin-city-mid.png" size="mid" id="4bc904f4017a3c57fe0016aa"/>
        064.        <image type="poster" url="http://i3.themoviedb.org/posters/6aa/4bc904f4017a3c57fe0016aa/sin-city-cover.png" size="cover" id="4bc904f4017a3c57fe0016aa"/>
        065.        <image type="poster" url="http://i3.themoviedb.org/posters/6aa/4bc904f4017a3c57fe0016aa/sin-city-thumb.png" size="thumb" id="4bc904f4017a3c57fe0016aa"/>
        066.        <image type="backdrop" url="http://i3.themoviedb.org/backdrops/614/4bc904d1017a3c57fe001614/sin-city-original.jpg" size="original" id="4bc904d1017a3c57fe001614"/>
        067.        <image type="backdrop" url="http://i2.themoviedb.org/backdrops/614/4bc904d1017a3c57fe001614/sin-city-poster.jpg" size="poster" id="4bc904d1017a3c57fe001614"/>
        068.        <image type="backdrop" url="http://i3.themoviedb.org/backdrops/614/4bc904d1017a3c57fe001614/sin-city-thumb.jpg" size="thumb" id="4bc904d1017a3c57fe001614"/>
        069.        <image type="backdrop" url="http://i3.themoviedb.org/backdrops/650/4bc904dd017a3c57fe001650/sin-city-original.jpg" size="original" id="4bc904dd017a3c57fe001650"/>
        070.        <image type="backdrop" url="http://i3.themoviedb.org/backdrops/650/4bc904dd017a3c57fe001650/sin-city-poster.jpg" size="poster" id="4bc904dd017a3c57fe001650"/>
        071.        <image type="backdrop" url="http://i1.themoviedb.org/backdrops/650/4bc904dd017a3c57fe001650/sin-city-thumb.jpg" size="thumb" id="4bc904dd017a3c57fe001650"/>
        072.        <image type="backdrop" url="http://i1.themoviedb.org/backdrops/684/4bc904e8017a3c57fe001684/sin-city-original.jpg" size="original" id="4bc904e8017a3c57fe001684"/>
        073.        <image type="backdrop" url="http://i2.themoviedb.org/backdrops/684/4bc904e8017a3c57fe001684/sin-city-poster.jpg" size="poster" id="4bc904e8017a3c57fe001684"/>
        074.        <image type="backdrop" url="http://i3.themoviedb.org/backdrops/684/4bc904e8017a3c57fe001684/sin-city-thumb.jpg" size="thumb" id="4bc904e8017a3c57fe001684"/>
        075.        <image type="backdrop" url="http://i1.themoviedb.org/backdrops/680/4bc904e5017a3c57fe001680/sin-city-original.jpg" size="original" id="4bc904e5017a3c57fe001680"/>
        076.        <image type="backdrop" url="http://i2.themoviedb.org/backdrops/680/4bc904e5017a3c57fe001680/sin-city-poster.jpg" size="poster" id="4bc904e5017a3c57fe001680"/>
        077.        <image type="backdrop" url="http://i3.themoviedb.org/backdrops/680/4bc904e5017a3c57fe001680/sin-city-thumb.jpg" size="thumb" id="4bc904e5017a3c57fe001680"/>
        078.        <image type="backdrop" url="http://i2.themoviedb.org/backdrops/67c/4bc904e5017a3c57fe00167c/sin-city-original.jpg" size="original" id="4bc904e5017a3c57fe00167c"/>
        079.        <image type="backdrop" url="http://i1.themoviedb.org/backdrops/67c/4bc904e5017a3c57fe00167c/sin-city-poster.jpg" size="poster" id="4bc904e5017a3c57fe00167c"/>
        080.        <image type="backdrop" url="http://i2.themoviedb.org/backdrops/67c/4bc904e5017a3c57fe00167c/sin-city-thumb.jpg" size="thumb" id="4bc904e5017a3c57fe00167c"/>
        081.        <image type="backdrop" url="http://i3.themoviedb.org/backdrops/678/4bc904e5017a3c57fe001678/sin-city-original.jpg" size="original" id="4bc904e5017a3c57fe001678"/>
        082.        <image type="backdrop" url="http://i2.themoviedb.org/backdrops/678/4bc904e5017a3c57fe001678/sin-city-poster.jpg" size="poster" id="4bc904e5017a3c57fe001678"/>
        083.        <image type="backdrop" url="http://i2.themoviedb.org/backdrops/678/4bc904e5017a3c57fe001678/sin-city-thumb.jpg" size="thumb" id="4bc904e5017a3c57fe001678"/>
        084.        <image type="backdrop" url="http://i1.themoviedb.org/backdrops/674/4bc904e4017a3c57fe001674/sin-city-original.jpg" size="original" id="4bc904e4017a3c57fe001674"/>
        085.        <image type="backdrop" url="http://i2.themoviedb.org/backdrops/674/4bc904e4017a3c57fe001674/sin-city-poster.jpg" size="poster" id="4bc904e4017a3c57fe001674"/>
        086.        <image type="backdrop" url="http://i2.themoviedb.org/backdrops/674/4bc904e4017a3c57fe001674/sin-city-thumb.jpg" size="thumb" id="4bc904e4017a3c57fe001674"/>
        087.        <image type="backdrop" url="http://i2.themoviedb.org/backdrops/670/4bc904e4017a3c57fe001670/sin-city-original.jpg" size="original" id="4bc904e4017a3c57fe001670"/>
        088.        <image type="backdrop" url="http://i1.themoviedb.org/backdrops/670/4bc904e4017a3c57fe001670/sin-city-poster.jpg" size="poster" id="4bc904e4017a3c57fe001670"/>
        089.        <image type="backdrop" url="http://i1.themoviedb.org/backdrops/670/4bc904e4017a3c57fe001670/sin-city-thumb.jpg" size="thumb" id="4bc904e4017a3c57fe001670"/>
        090.        <image type="backdrop" url="http://i1.themoviedb.org/backdrops/66c/4bc904e1017a3c57fe00166c/sin-city-original.jpg" size="original" id="4bc904e1017a3c57fe00166c"/>
        091.        <image type="backdrop" url="http://i2.themoviedb.org/backdrops/66c/4bc904e1017a3c57fe00166c/sin-city-poster.jpg" size="poster" id="4bc904e1017a3c57fe00166c"/>
        092.        <image type="backdrop" url="http://i2.themoviedb.org/backdrops/66c/4bc904e1017a3c57fe00166c/sin-city-thumb.jpg" size="thumb" id="4bc904e1017a3c57fe00166c"/>
        093.        <image type="backdrop" url="http://i1.themoviedb.org/backdrops/668/4bc904e1017a3c57fe001668/sin-city-original.jpg" size="original" id="4bc904e1017a3c57fe001668"/>
        094.        <image type="backdrop" url="http://i2.themoviedb.org/backdrops/668/4bc904e1017a3c57fe001668/sin-city-poster.jpg" size="poster" id="4bc904e1017a3c57fe001668"/>
        095.        <image type="backdrop" url="http://i2.themoviedb.org/backdrops/668/4bc904e1017a3c57fe001668/sin-city-thumb.jpg" size="thumb" id="4bc904e1017a3c57fe001668"/>
        096.        <image type="backdrop" url="http://i1.themoviedb.org/backdrops/664/4bc904e1017a3c57fe001664/sin-city-original.jpg" size="original" id="4bc904e1017a3c57fe001664"/>
        097.        <image type="backdrop" url="http://i3.themoviedb.org/backdrops/664/4bc904e1017a3c57fe001664/sin-city-poster.jpg" size="poster" id="4bc904e1017a3c57fe001664"/>
        098.        <image type="backdrop" url="http://i3.themoviedb.org/backdrops/664/4bc904e1017a3c57fe001664/sin-city-thumb.jpg" size="thumb" id="4bc904e1017a3c57fe001664"/>
        099.        <image type="backdrop" url="http://i3.themoviedb.org/backdrops/660/4bc904e0017a3c57fe001660/sin-city-original.jpg" size="original" id="4bc904e0017a3c57fe001660"/>
        100.        <image type="backdrop" url="http://i3.themoviedb.org/backdrops/660/4bc904e0017a3c57fe001660/sin-city-poster.jpg" size="poster" id="4bc904e0017a3c57fe001660"/>
        101.        <image type="backdrop" url="http://i3.themoviedb.org/backdrops/660/4bc904e0017a3c57fe001660/sin-city-thumb.jpg" size="thumb" id="4bc904e0017a3c57fe001660"/>
        102.        <image type="backdrop" url="http://i3.themoviedb.org/backdrops/65c/4bc904e0017a3c57fe00165c/sin-city-original.jpg" size="original" id="4bc904e0017a3c57fe00165c"/>
        103.        <image type="backdrop" url="http://i1.themoviedb.org/backdrops/65c/4bc904e0017a3c57fe00165c/sin-city-poster.jpg" size="poster" id="4bc904e0017a3c57fe00165c"/>
        104.        <image type="backdrop" url="http://i2.themoviedb.org/backdrops/65c/4bc904e0017a3c57fe00165c/sin-city-thumb.jpg" size="thumb" id="4bc904e0017a3c57fe00165c"/>
        105.        <image type="backdrop" url="http://i3.themoviedb.org/backdrops/658/4bc904de017a3c57fe001658/sin-city-original.jpg" size="original" id="4bc904de017a3c57fe001658"/>
        106.        <image type="backdrop" url="http://i1.themoviedb.org/backdrops/658/4bc904de017a3c57fe001658/sin-city-poster.jpg" size="poster" id="4bc904de017a3c57fe001658"/>
        107.        <image type="backdrop" url="http://i2.themoviedb.org/backdrops/658/4bc904de017a3c57fe001658/sin-city-thumb.jpg" size="thumb" id="4bc904de017a3c57fe001658"/>
        108.        <image type="backdrop" url="http://i1.themoviedb.org/backdrops/654/4bc904dd017a3c57fe001654/sin-city-original.jpg" size="original" id="4bc904dd017a3c57fe001654"/>
        109.        <image type="backdrop" url="http://i2.themoviedb.org/backdrops/654/4bc904dd017a3c57fe001654/sin-city-poster.jpg" size="poster" id="4bc904dd017a3c57fe001654"/>
        110.        <image type="backdrop" url="http://i3.themoviedb.org/backdrops/654/4bc904dd017a3c57fe001654/sin-city-thumb.jpg" size="thumb" id="4bc904dd017a3c57fe001654"/>
        111.      </images>
        112.      <cast>
        113.        <person url="http://www.themoviedb.org/person/2293" name="Frank Miller" department="Directing" thumb="" character="" job="Director" id="2293"/>
        114.        <person url="http://www.themoviedb.org/person/2294" name="Robert Rodriguez" department="Directing" thumb="" character="" job="Director" id="2294"/>
        115.        <person url="http://www.themoviedb.org/person/138" name="Quentin Tarantino" department="Directing" thumb="" character="Special Guest Director" job="Director" id="138"/>
        116.        <person url="http://www.themoviedb.org/person/2293" name="Frank Miller" department="Writing" thumb="" character="" job="Author" id="2293"/>
        117.        <person url="http://www.themoviedb.org/person/62" name="Bruce Willis" department="Actors" thumb="" character="   Hartigan" job="Actor" id="62"/>
        118.        <person url="http://www.themoviedb.org/person/2295" name="Mickey Rourke" department="Actors" thumb="http://i2.themoviedb.org/profiles/086/4bcf7797017a3c63ed000086/mickey-rourke-thumb.jpg" character="Marv" job="Actor" id="2295"/>
        119.        <person url="http://www.themoviedb.org/person/2296" name="Clive Owen" department="Actors" thumb="" character="Dwight" job="Actor" id="2296"/>
        120.        <person url="http://www.themoviedb.org/person/56731" name="Jessica Alba" department="Actors" thumb="http://i1.themoviedb.org/profiles/0c9/4bcc3ba0017a3c0f340000c9/jessica-alba-thumb.jpg" character="Nancy Callahan" job="Actor" id="56731"/>
        121.        <person url="http://www.themoviedb.org/person/109" name="Elijah Wood" department="Actors" thumb="http://i2.themoviedb.org/profiles/00e/4bc9f571017a3c0e9100000e/elijah-wood-thumb.jpg" character="Kevin" job="Actor" id="109"/>
        122.        <person url="http://www.themoviedb.org/person/2299" name="Josh Hartnett" department="Actors" thumb="" character="The Salesman" job="Actor" id="2299"/>
        123.        <person url="http://www.themoviedb.org/person/5911" name="Elizabeth Avellan" department="Production" thumb="" character="" job="Producer" id="5911"/>
        124.        <person url="http://www.themoviedb.org/person/4500" name="John Debney" department="Sound" thumb="" character="" job="Original Music Composer" id="4500"/>
        125.        <person url="http://www.themoviedb.org/person/5912" name="Graeme Revell" department="Sound" thumb="" character="" job="Original Music Composer" id="5912"/>
        126.        <person url="http://www.themoviedb.org/person/2294" name="Robert Rodriguez" department="Sound" thumb="" character="" job="Original Music Composer" id="2294"/>
        127.        <person url="http://www.themoviedb.org/person/2294" name="Robert Rodriguez" department="Camera" thumb="" character="" job="Director of Photography" id="2294"/>
        128.        <person url="http://www.themoviedb.org/person/2294" name="Robert Rodriguez" department="Editing" thumb="" character="" job="Editor" id="2294"/>
        129.        <person url="http://www.themoviedb.org/person/5913" name="Beth Sepko" department="Production" thumb="" character="" job="Casting" id="5913"/>
        130.        <person url="http://www.themoviedb.org/person/5914" name="Mary Vernieu" department="Production" thumb="" character="" job="Casting" id="5914"/>
        131.        <person url="http://www.themoviedb.org/person/5915" name="Jaime King" department="Actors" thumb="http://i3.themoviedb.org/profiles/0ce/4bcc3bbd017a3c0f340000ce/jaime-king-thumb.jpg" character="Goldie/Wendy" job="Actor" id="5915"/>
        132.        <person url="http://www.themoviedb.org/person/585" name="Rutger Hauer" department="Actors" thumb="" character="Cardinal Roark" job="Actor" id="585"/>
        133.        <person url="http://www.themoviedb.org/person/1121" name="Benicio Del Toro" department="Actors" thumb="" character="Jackie Boy" job="Actor" id="1121"/>
        134.        <person url="http://www.themoviedb.org/person/5916" name="Rosario Dawson" department="Actors" thumb="http://i3.themoviedb.org/profiles/0b2/4bcc3bde017a3c0f320000b2/rosario-dawson-thumb.jpg" character="Gail" job="Actor" id="5916"/>
        135.        <person url="http://www.themoviedb.org/person/61981" name="Michael Clarke Duncan" department="Actors" thumb="http://i3.themoviedb.org/profiles/033/4bd3e1eb017a3c7fa6000033/michael-clarke-duncan-thumb.jpg" character="Manute" job="Actor" id="61981"/>
        136.        <person url="http://www.themoviedb.org/person/6278" name="Devon Aoki" department="Actors" thumb="http://i1.themoviedb.org/profiles/071/4bcc3bfe017a3c0f2a000071/devon-aoki-thumb.jpg" character="Miho" job="Actor" id="6278"/>
        137.        <person url="http://www.themoviedb.org/person/6279" name="Alexis Bledel" department="Actors" thumb="http://i2.themoviedb.org/profiles/0b6/4bcc3c1e017a3c0f320000b6/alexis-bledel-thumb.jpg" character="Becky" job="Actor" id="6279"/>
        138.        <person url="http://www.themoviedb.org/person/6280" name="Powers Boothe" department="Actors" thumb="" character="Senator Roark" job="Actor" id="6280"/>
        139.        <person url="http://www.themoviedb.org/person/6407" name="Marley Shelton" department="Actors" thumb="http://i1.themoviedb.org/profiles/0bb/4bcc3c3c017a3c0f320000bb/marley-shelton-thumb.jpg" character="The Customer" job="Actor" id="6407"/>
        140.        <person url="http://www.themoviedb.org/person/6408" name="Nick Stahl" department="Actors" thumb="" character="Roark Jr./The Yellow Bastard" job="Actor" id="6408"/>
        141.        <person url="http://www.themoviedb.org/person/147" name="Michael Madsen" department="Actors" thumb="" character="Bob" job="Actor" id="147"/>
        142.        <person url="http://www.themoviedb.org/person/2139" name="Makenzie Vega" department="Actors" thumb="" character="Nancy (11 Years)" job="Actor" id="2139"/>
        143.        <person url="http://www.themoviedb.org/person/328" name="Brittany Murphy" department="Actors" thumb="http://i2.themoviedb.org/profiles/095/4bcc2ffb017a3c0f26000095/brittany-murphy-thumb.jpg" character="Shellie" job="Actor" id="328"/>
        144.        <person url="http://www.themoviedb.org/person/17832" name="Carla Gugino" department="Actors" thumb="" character="Lucille" job="Actor" id="17832"/>
        145.      </cast>
        146.      <last_modified_at>2010-04-26 08:46:23</last_modified_at>
        147.    </movie>
        148.  </movies>
        149.</OpenSearchDescription>*/

        private int GetMovieID(string moviename, out string newsearchname)
        {
            List<int> listIDs = new List<int>();
            List<string> listNames = new List<string>();

            newsearchname = moviename;

            try
            {
                string apikey = "cd4e4889bc9229dbe5fcfc51db5e421c";
                string searchstring = moviename;
                string lang = "de";
                string request = "http://api.themoviedb.org/2.1/Movie.search/" + lang + "/xml/" + apikey + "/" + searchstring;

                ShowMessage("Send \"Movie.search\" request ...");

                WebRequest req = WebRequest.Create(request);
                WebResponse response = req.GetResponse();
                Stream stream = response.GetResponseStream();

                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.Load(stream);

                stream.Close();

                XmlNode nodeRoot = xmlDoc.SelectSingleNode("OpenSearchDescription");

                if (nodeRoot != null)
                {
                    XmlNode nodeMovies = nodeRoot.SelectSingleNode("movies");
                    if (nodeMovies != null)
                    {
                        XmlNodeList nodesMovies = nodeMovies.SelectNodes("movie");

                        foreach (XmlNode nodeMovie in nodesMovies)
                        {
                            ShowMessage("Movie found: ID = " + GetXmlValue(nodeMovie, "id") + ", Name = " + GetXmlValue(nodeMovie, "name"));

                            listNames.Add(GetXmlValue(nodeMovie, "name"));
                            listIDs.Add(int.Parse(GetXmlValue(nodeMovie, "id")));
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ShowMessage(ex.Message);
            }

            if (listIDs.Count == 0)
            {
                ItemChooser chooser = new ItemChooser();
                chooser.HeaderText = "Suche: " + moviename;
                chooser.NewSearchText = moviename;
                for (int i = 0; i < listIDs.Count; i++)
                {
                    chooser.AddItem(listIDs[i], listNames[i]);
                }
                DialogResult result = chooser.ShowDialog();
                if (result == DialogResult.OK)
                {
                    return chooser.GetSelectedItemID();
                }
                else if (result == DialogResult.Retry)
                {
                    return GetMovieID(chooser.NewSearchText, out newsearchname);
                }
                else if (result == DialogResult.Ignore)
                {
                    newsearchname = chooser.NewSearchText;
                    return -2;
                }
                else
                {
                    return -1;
                }
            }
            else if (listIDs.Count > 1)
            {
                ItemChooser chooser = new ItemChooser();
                chooser.HeaderText = "Suche: " + moviename;
                chooser.NewSearchText = moviename;
                for (int i = 0; i < listIDs.Count; i++)
                {
                    chooser.AddItem(listIDs[i], listNames[i]);
                }
                DialogResult result = chooser.ShowDialog();
                if (result == DialogResult.OK)
                {
                    return chooser.GetSelectedItemID();
                }
                else if (result == DialogResult.Retry)
                {
                    return GetMovieID(chooser.NewSearchText, out newsearchname);
                }
                else if (result == DialogResult.Ignore)
                {
                    newsearchname = chooser.NewSearchText;
                    return -2;
                }
                else
                {
                    return -1;
                }
            }
            else
            {
                return listIDs[0];
            }
        }

        private MovieInformation GetMovieInfos(string moviename, string moviedirectory)
        {
            MovieInformation movieInfo = new MovieInformation();
            if (!moviedirectory.EndsWith(@"\"))
                moviedirectory += @"\";

            try
            {
                bool bGoogleSearch = false;
                bool bCoverFound = false;
                bool bCoverOriginalFound = false;

                string apikey = "cd4e4889bc9229dbe5fcfc51db5e421c";
                string searchstring = moviename;
                string lang = "de";
                string googlesearchtext = "";
                string movie_id = GetMovieID(moviename, out googlesearchtext).ToString();

                if (movie_id.Equals("-1"))
                {
                    return null;
                }
                else if (movie_id.Equals("-2"))
                {
                    bGoogleSearch = true;
                }

                if (!bGoogleSearch)
                {
                    string request = "http://api.themoviedb.org/2.1/Movie.getInfo/" + lang + "/xml/" + apikey + "/" + movie_id;

                    ShowMessage("Send \"Movie.getInfo\" request ...");

                    WebRequest req = WebRequest.Create(request);
                    WebResponse response = req.GetResponse();
                    Stream stream = response.GetResponseStream();

                    XmlDocument xmlDoc = new XmlDocument();
                    xmlDoc.Load(stream);

                    stream.Close();

                    XmlNode nodeRoot = xmlDoc.SelectSingleNode("OpenSearchDescription");

                    if (nodeRoot != null)
                    {
                        XmlNode nodeMovies = nodeRoot.SelectSingleNode("movies");
                        if (nodeMovies != null)
                        {
                            XmlNodeList nodesMovies = nodeMovies.SelectNodes("movie");

                            if (nodesMovies == null || nodesMovies.Count == 0)
                            {
                                ShowMessage("No Movie was found (ID: " + movie_id + ")");
                            }

                            foreach (XmlNode nodeMovie in nodesMovies)
                            {
                                ShowMessage("get movie data ...");

                                //string popularity = GetXmlValue(nodeMovie, "popularity");
                                movieInfo.Description = GetXmlValue(nodeMovie, "overview");
                                movieInfo.title = GetXmlValue(nodeMovie, "name");
                                movieInfo.AlternativeTitles = GetXmlValue(nodeMovie, "alternative_name");
                                //string type = GetXmlValue(nodeMovie, "type");
                                movieInfo.Rating = GetXmlValue(nodeMovie, "rating");
                                movieInfo.releasedate = GetXmlValue(nodeMovie, "released");
                                movieInfo.TheMovieDbId = GetXmlValue(nodeMovie, "id");
                                movieInfo.IMDB = GetXmlValue(nodeMovie, "imdb_id");
                                //movieInfo.homepage = link = GetXmlValue(nodeMovie, "url");
                                movieInfo.Runtime_Original = GetXmlValue(nodeMovie, "runtime");
                                movieInfo.Budget = GetXmlValue(nodeMovie, "budget");
                                movieInfo.Revenue = GetXmlValue(nodeMovie, "revenue");
                                //movieInfo.homepage = GetXmlValue(nodeMovie, "homepage");
                                movieInfo.Trailer = GetXmlValue(nodeMovie, "trailer");

                                XmlNode nodeImages = nodeMovie.SelectSingleNode("images");
                                if (nodeImages != null)
                                {
                                    XmlNodeList nodesImages = nodeImages.SelectNodes("image");

                                    if (!Directory.Exists(moviedirectory + @"Backdrops\"))
                                    {
                                        Directory.CreateDirectory(moviedirectory + @"Backdrops\");
                                    }

                                    ShowMessage("get movie images ...");
                                    int backdropId = 0;
                                    int backdropMAX = _Settings.BackdropImageCount;

                                    foreach (XmlNode nodeImage in nodesImages)
                                    {
                                        string image_url = GetXmlAttributeValue(nodeImage, "url");
                                        string image_type = GetXmlAttributeValue(nodeImage, "type");
                                        string image_size = GetXmlAttributeValue(nodeImage, "size");
                                        string image_id = GetXmlAttributeValue(nodeImage, "id");

                                        try
                                        {
                                            if (image_type.ToLower().Trim().Equals("poster"))
                                            {
                                                // folder.jpg, folder_original.jpg
                                                if (!bCoverFound && image_size.ToLower().Trim().Equals("cover"))
                                                {
                                                    ShowMessage("get movie image: folder (" + image_id + ") ...");

                                                    WebRequest reqI = WebRequest.Create(image_url);
                                                    WebResponse responseI = reqI.GetResponse();
                                                    Stream streamI = responseI.GetResponseStream();

                                                    Image image = Image.FromStream(streamI);

                                                    bCoverFound = true;
                                                    image.Save(moviedirectory + "folder.jpg");

                                                    movieInfo.Folder = moviedirectory + "folder.jpg";
                                                    ShowMessage("save folder image ...");
                                                }
                                                else if (!bCoverOriginalFound && image_size.ToLower().Trim().Equals("original"))
                                                {
                                                    ShowMessage("get movie image: folder_original (" + image_id + ") ...");

                                                    WebRequest reqI = WebRequest.Create(image_url);
                                                    WebResponse responseI = reqI.GetResponse();
                                                    Stream streamI = responseI.GetResponseStream();

                                                    Image image = Image.FromStream(streamI);

                                                    bCoverOriginalFound = true;
                                                    image.Save(moviedirectory + "folder_original.jpg");
                                                    ShowMessage("save folder image (original) ...");
                                                }
                                            }
                                            else if (image_type.ToLower().Trim().Equals("backdrop") && (backdropId < backdropMAX || backdropMAX == -1))
                                            {
                                                // backdrops
                                                if (image_size.ToLower().Trim().Equals("original"))
                                                {
                                                    ShowMessage("get movie image: backdrop #" + (backdropId + 1).ToString() + " (" + image_id + ") ...");

                                                    WebRequest reqI = WebRequest.Create(image_url);
                                                    WebResponse responseI = reqI.GetResponse();
                                                    Stream streamI = responseI.GetResponseStream();

                                                    Image image = Image.FromStream(streamI);

                                                    image.Save(moviedirectory + @"Backdrops\" + image_id + ".jpg");

                                                    //movieInfo.Backdrop += "{" + moviedirectory + @"Backdrops\" + image_id + ".jpg" + "}";
                                                    if (movieInfo.Backdrop != null && !movieInfo.Backdrop.Equals(""))
                                                    {
                                                        movieInfo.Backdrop += ",";
                                                    }

                                                    movieInfo.Backdrop += "\"" + moviedirectory + @"Backdrops\" + image_id + ".jpg\"";
                                                    ShowMessage("save backdrop image ...");

                                                    backdropId++;
                                                }
                                            }
                                        }
                                        catch (Exception ex)
                                        {
                                            ShowMessage(ex.Message);
                                        }
                                    }
                                }

                                XmlNode nodeCategories = nodeMovie.SelectSingleNode("categories");
                                if (nodeCategories != null)
                                {
                                    XmlNodeList nodesCategory = nodeCategories.SelectNodes("category");

                                    ShowMessage("get movie categories ...");

                                    foreach (XmlNode nodeCategory in nodesCategory)
                                    {
                                        string cat_name = GetXmlAttributeValue(nodeCategory, "name");
                                        string cat_type = GetXmlAttributeValue(nodeCategory, "type");

                                        if (cat_type.ToLower().Trim().Equals("genre"))
                                        {
                                            movieInfo.Categories += "{" + cat_name + "}";
                                        }
                                    }
                                }

                                XmlNode nodeCountries = nodeMovie.SelectSingleNode("countries");
                                if (nodeCountries != null)
                                {
                                    XmlNodeList nodesCountry = nodeCountries.SelectNodes("country");

                                    ShowMessage("get movie countries ...");

                                    foreach (XmlNode nodeCountry in nodesCountry)
                                    {
                                        string country_name = GetXmlAttributeValue(nodeCountry, "name");

                                        movieInfo.ProductionCountry += "{" + country_name + "}";
                                    }
                                }

                                XmlNode nodeCast = nodeMovie.SelectSingleNode("cast");
                                if (nodeCast != null)
                                {
                                    XmlNodeList nodesPersons = nodeCast.SelectNodes("person");

                                    ShowMessage("get movie casts ...");

                                    foreach (XmlNode nodePerson in nodesPersons)
                                    {
                                        string person_name = GetXmlAttributeValue(nodePerson, "name");
                                        string person_job = GetXmlAttributeValue(nodePerson, "job").ToLower().Trim();

                                        if (person_job.Equals("actor"))
                                        {
                                            movieInfo.People_Actors += "{" + person_name + "}";
                                        }
                                        else if (person_job.Equals("director"))
                                        {
                                            movieInfo.People_Director += "{" + person_name + "}";
                                        }
                                        else if (person_job.Equals("author"))
                                        {
                                            movieInfo.People_Author += "{" + person_name + "}";
                                        }
                                        else if (person_job.Equals("editor"))
                                        {
                                            movieInfo.People_Editor += "{" + person_name + "}";
                                        }
                                        else if (person_job.Equals("producer"))
                                        {
                                            movieInfo.People_Producer += "{" + person_name + "}";
                                        }
                                        else if (person_job.Equals("casting"))
                                        {
                                            movieInfo.People_Casting += "{" + person_name + "}";
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                else
                {
                    ShowMessage("get movie data ...");

                    //string popularity = GetXmlValue(nodeMovie, "popularity");
                    movieInfo.Description = "";
                    movieInfo.title = moviename;
                    movieInfo.AlternativeTitles = moviename;
                    //string type = GetXmlValue(nodeMovie, "type");
                    movieInfo.Rating = "0.0";
                    movieInfo.releasedate = "";
                    movieInfo.TheMovieDbId = "";
                    movieInfo.IMDB = "";
                    //movieInfo.homepage = link = GetXmlValue(nodeMovie, "url");
                    movieInfo.Runtime_Original = "";
                    movieInfo.Budget = "";
                    movieInfo.Revenue = "";
                    //movieInfo.homepage = GetXmlValue(nodeMovie, "homepage");
                    movieInfo.Trailer = "";
                }

                // Google Bildersuche
                if (!bCoverFound && !bCoverOriginalFound)
                {
                    ShowMessage("get google movie images ...");

                    Image img = GetGoogleImage(googlesearchtext + " poster");
                    if (img != null)
                    {
                        img.Save(moviedirectory + "folder.jpg");
                        movieInfo.Folder = moviedirectory + "folder.jpg";
                    }
                }
            }
            catch (Exception ex)
            {
                ShowMessage(ex.Message);

                return null;
            }

            return movieInfo;
        }

        private string GetXmlValue(XmlNode nodeRoot, String tagName)
        {
            try
            {
                return nodeRoot.SelectSingleNode(tagName).InnerXml;
            }
            catch { }

            return "";
        }

        private string GetXmlAttributeValue(XmlNode nodeRoot, String attributeName)
        {
            try
            {
                return nodeRoot.Attributes.GetNamedItem(attributeName).Value;
            }
            catch { }

            return "";
        }

        private void GetMediaInfo(string movieFilename, ref MovieInformation movieInfo)
        {
            if (File.Exists(movieFilename))
            {
                //filedate, videocodec, videobitrate, videowidth, videoheight, 
                //videoframerate, audiocodec, audiobitrate, audiochannels

                MediaInfo mi = new MediaInfo();

                mi.Open(movieFilename);

                movieInfo.filedate = mi.Get(StreamKind.General, 0, "File_Created_Date");
                movieInfo.videocodec = mi.Get(StreamKind.Video, 0, "CodecID");
                movieInfo.videobitrate = mi.Get(StreamKind.Video, 0, "BitRate");
                movieInfo.videowidth = mi.Get(StreamKind.Video, 0, "Width");
                movieInfo.videoheight = mi.Get(StreamKind.Video, 0, "Height");
                movieInfo.videoframerate = mi.Get(StreamKind.Video, 0, "FrameRate");
                movieInfo.audiocodec = mi.Get(StreamKind.Audio, 0, "CodecID");
                movieInfo.audiobitrate = mi.Get(StreamKind.Audio, 0, "BitRate");
                movieInfo.audiochannels = mi.Get(StreamKind.Audio, 0, "Channel(s)");

                mi.Close();
            }
        }

        private void ShowMediaInfo(string movieFilename)
        {
            if (File.Exists(movieFilename))
            {
                //filedate, videocodec, videobitrate, videowidth, videoheight, 
                //videoframerate, audiocodec, audiobitrate, audiochannels

                string text = "";

                MediaInfo mi = new MediaInfo();

                mi.Open(movieFilename);

                text += "FileName: " + mi.Get(StreamKind.General, 0, "FileName") + "\r\n";
                text += "FileExtension: " + mi.Get(StreamKind.General, 0, "FileExtension") + "\r\n";
                text += "Title: " + mi.Get(StreamKind.General, 0, "Title") + "\r\n";
                text += "FileSize: " + string.Format("{0:0,0} Bytes", Int64.Parse(mi.Get(StreamKind.General, 0, "FileSize"))) + "\r\n";
                text += "Duration: " + mi.Get(StreamKind.General, 0, "Duration/String3") + "\r\n";
                text += "Language: " + mi.Get(StreamKind.General, 0, "Language/String1") + "\r\n\r\n";

                text += "FileCreatedDate: " + mi.Get(StreamKind.General, 0, "File_Created_Date") + "\r\n\r\n";

                text += "Video CodecID: " + mi.Get(StreamKind.Video, 0, "CodecID") + "\r\n";
                text += "Video BitRate: " + mi.Get(StreamKind.Video, 0, "BitRate") + "\r\n";
                text += "Video Width: " + mi.Get(StreamKind.Video, 0, "Width") + "\r\n";
                text += "Video Height: " + mi.Get(StreamKind.Video, 0, "Height") + "\r\n";
                text += "Video FrameRate: " + mi.Get(StreamKind.Video, 0, "FrameRate") + "\r\n\r\n";

                text += "Audio CodecID: " + mi.Get(StreamKind.Audio, 0, "CodecID") + "\r\n";
                text += "Audio BitRate: " + mi.Get(StreamKind.Audio, 0, "BitRate") + "\r\n";
                text += "Audio Channel(s): " + mi.Get(StreamKind.Audio, 0, "Channel(s)") + "\r\n";

                mi.Close();

                MediaInfoForm form = new MediaInfoForm(text);
                form.ShowDialog();
            }
        }

        void MainFormFormClosing(object sender, FormClosingEventArgs e)
        {
            _Settings.Save(_SettingsFilename);
        }

        void Button2Click(object sender, EventArgs e)
        {
            // Test
            //MovieInformation movieInfo = GetMovieInfos("Schindlers Liste", @"E:\Test\SL\");
            //movieInfo.WriteInfoFile(@"E:\Test\SL\");
            //movieInfo.AddToDB(_Settings.ConfigDirectory, _Settings.SQLiteV3MyMovies, _Settings.UTF8);

            MovieInformation mi = new MovieInformation();

            GetMediaInfo(@"C:\Dokumente und Einstellungen\Christian\Eigene Dateien\Eigene Videos\mika_race.wmv", ref mi);
        }

        private void BtnRefreshRecordings_Click(object sender, EventArgs e)
        {
            RefreshRecordingList();
        }

        private void btnRefreshMyMovies_Click(object sender, EventArgs e)
        {
            RefreshMyMoviesList();
        }

        void TsbtnChangeTitleClick(object sender, EventArgs e)
        {
            if (listViewMyMovies.SelectedItems.Count > 0)
            {
                TextDialog tdialog = new TextDialog("Titel ändern");
                tdialog.NewText = _Movies[listViewMyMovies.SelectedIndices[0]].Title;

                if (tdialog.ShowDialog() == DialogResult.OK)
                {
                    MovieInformation.UpdateItemDB(_Movies[listViewMyMovies.SelectedIndices[0]].ID, "title", tdialog.NewText, _Settings.ConfigDirectory, _Settings.MyMoviesDBFile, _Settings.SQLiteV3MyMovies, _Settings.UTF8);
                    RefreshMyMoviesList();
                }
            }
        }

        void TsbtnChangePathClick(object sender, EventArgs e)
        {
            if (listViewMyMovies.SelectedItems.Count > 0)
            {
                TextDialog tdialog = new TextDialog("Pfad ändern");
                tdialog.NewText = _Movies[listViewMyMovies.SelectedIndices[0]].Path;

                if (tdialog.ShowDialog() == DialogResult.OK)
                {
                    MovieInformation.UpdateItemDB(_Movies[listViewMyMovies.SelectedIndices[0]].ID, "path", tdialog.NewText, _Settings.ConfigDirectory, _Settings.MyMoviesDBFile, _Settings.SQLiteV3MyMovies, _Settings.UTF8);
                    RefreshMyMoviesList();
                }
            }
        }

        void TsbtnClipboardNameClick(object sender, EventArgs e)
        {
            if (listViewMyMovies.SelectedItems.Count > 0)
            {
                System.Windows.Forms.Clipboard.SetDataObject(listViewMyMovies.SelectedIndices[0].ToString(), true);
            }
        }

        public Image GetGoogleImage(string s)
        {
            List<string> lstUri = GetGoogleImages(s);

            Image resImage = null;

            if (lstUri.Count > 0)
            {
                ChooseImageDlg dlg = new ChooseImageDlg();
                dlg.Images = lstUri;

                if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {

                }
                /*WebRequest reqI = WebRequest.Create(lstUri[0]);
                WebResponse responseI = reqI.GetResponse();
                Stream streamI = responseI.GetResponseStream();

                resImage = Image.FromStream(streamI);*/
            }

            return resImage;
        }

        public List<string> GetGoogleImages(string s)
        {
            string strSearch = "http://www.google.de/images?q=" + s + "&hl=de&um=1&ie=UTF-8&source=og&sa=N&tab=wi";

            WebRequest request = WebRequest.Create(strSearch);
            request.Credentials = System.Net.CredentialCache.DefaultCredentials;
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            if (response.StatusCode == HttpStatusCode.OK)
            {
                StreamReader sr = new StreamReader(response.GetResponseStream());
                string source = sr.ReadToEnd();
                sr.Close();
                List<string> links = new List<string>();

                //string regexImgSrc = @"<img[^>]*?src\s*=\s*[""']?([^'"" >]+?)[ '""][^>]*?>";
                string regexImgSrc = @"imgurl\\x3d(?<url>.*?)\\x26imgrefurl";
                MatchCollection matchesImgSrc = Regex.Matches(source, regexImgSrc, RegexOptions.IgnoreCase | RegexOptions.Singleline);
                foreach (Match m in matchesImgSrc)
                {
                    string value = m.Groups["url"].Value;

                    int li = value.LastIndexOf("http://");
                    if (li >= 0)
                    {
                        value = value.Substring(li);
                        links.Add(value);
                    }
                }
                return links;
            }

            return null;
        }

        void ListMyMoviesDoubleClick(object sender, EventArgs e)
        {
            if (listViewMyMovies.SelectedItems.Count > 0)
            {
                MovieInformation movieInfo = MovieInformation.GetFromDB(_Movies[listViewMyMovies.SelectedIndices[0]].ID, _Settings.ConfigDirectory, _Settings.SQLiteV3MyMovies, _Settings.UTF8);

                MovieInformationDialog dlg = new MovieInformationDialog(movieInfo);
                if (dlg.ShowDialog() == DialogResult.OK)
                {
                    movieInfo = dlg.MovieInfo;

                    if (_Settings.DBUsed)
                    {
                        movieInfo.UpdateDB(_Movies[listViewMyMovies.SelectedIndices[0]].ID, _Settings.ConfigDirectory, _Settings.MyMoviesDBFile, _Settings.SQLiteV3MyMovies, _Settings.UTF8);
                    }
                    else
                    {
                        movieInfo.WriteInfoFile(movieInfo.path);
                    }
                }
            }
        }

        void EinstellungenToolStripMenuItemClick(object sender, EventArgs e)
        {
            SettingsForm form = new SettingsForm(_Settings);
            if (form.ShowDialog() == DialogResult.OK)
            {
                _Settings.Save(_SettingsFilename);
            }
        }

        void BeendenToolStripMenuItemClick(object sender, EventArgs e)
        {
            Close();
        }

        void ListViewRecordingsDoubleClick(object sender, EventArgs e)
        {
            if (listViewRecordings.SelectedItems.Count > 0)
            {
                ShowMediaInfo(_Recordings[listViewRecordings.SelectedIndices[0]].Filename);
            }
        }

        void DateiInformationenAnzeigenToolStripMenuItemClick(object sender, EventArgs e)
        {
            if (listViewMyMovies.SelectedItems.Count > 0)
            {
                ShowMediaInfo(_Movies[listViewMyMovies.SelectedIndices[0]].Filename);
            }
        }

        void ÜberToolStripMenuItemClick(object sender, EventArgs e)
        {
            AboutBox form = new AboutBox();
            form.ShowDialog();
        }

        void FilmHinzufügenToolStripMenuItemClick(object sender, EventArgs e)
        {
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                // todo add movie
                listMessages.Items.Clear();

                try
                {
                    this.Cursor = Cursors.WaitCursor;

                    FileInfo fi = new FileInfo(openFileDialog.FileName);

                    string movieName = fi.Name.Replace(fi.Extension, "");

                    TextDialog dlg = new TextDialog("Name des Films");
                    dlg.NewText = movieName;
                    if (dlg.ShowDialog() == DialogResult.OK)
                    {
                        movieName = dlg.NewText;
                    }

                    String strFilenameSrc = openFileDialog.FileName;
                    String strDirnameDest = _Settings.MyMoviesDirectory + movieName.Replace("'", "") + @"\";
                    String strFilenameDest = strDirnameDest + movieName.Replace("'", "") + fi.Extension;

                    if (!Directory.Exists(strDirnameDest))
                    {
                        Directory.CreateDirectory(strDirnameDest);
                    }

                    if (File.Exists(strFilenameSrc))
                    {
                        File.Copy(strFilenameSrc, strFilenameDest);

                        MovieInformation movieInfo = GetMovieInfos(movieName, strDirnameDest);
                        if (movieInfo != null)
                        {
                            movieInfo.filename = strFilenameDest.Replace("\"", "");
                            movieInfo.path = strDirnameDest.Replace("\"", "");

                            ShowMessage("get videofile media informations ...");

                            GetMediaInfo(strFilenameDest, ref movieInfo);

                            movieInfo.title = movieInfo.title.Replace("\"", "");
                            movieInfo.Description = movieInfo.Description.Replace("\"", "");
                            movieInfo.AlternativeTitles = movieInfo.AlternativeTitles.Replace("\"", "");

                            if (_Settings.DBUsed)
                            {
                                movieInfo.AddToDB(_Settings.ConfigDirectory, _Settings.MyMoviesDBFile, _Settings.SQLiteV3MyMovies, _Settings.UTF8);
                            }
                            else
                            {
                                movieInfo.WriteInfoFile(strDirnameDest);
                            }
                        }

                        if (MessageBox.Show("Soll die Datei \"" + fi.Name + "\" von ihrem usprünglichen Standort gelöscht werden?", "Datei löschen", MessageBoxButtons.YesNo) == DialogResult.Yes)
                        {
                            File.Delete(strFilenameSrc);
                        }
                    }
                    else
                    {
                        throw new Exception("File " + strFilenameSrc + " does not exist");
                    }

                }
                catch (Exception ex)
                {
                    ShowMessage(ex.Message);
                }
                finally
                {
                    ShowMessage("get movie informations finished");

                    this.Cursor = Cursors.Default;
                }

                RefreshMyMoviesList();
            }
        }
    }

    public class Recording
    {
        public int ID { get; set; }
        public string Filename { get; set; }
        public string Channel { get; set; }
        public string Title { get; set; }
        public string Description { get; set; }
    }

    public class Movie
    {
        public int ID { get; set; }
        public string Filename { get; set; }
        public string Path { get; set; }
        public string Title { get; set; }
    }
}